import os
import shutil
import sys,subprocess,threading
import threading

from PySide6.QtWidgets import QApplication,QWidget,QVBoxLayout,QLabel
from PySide6.QtCore import QTimer,Qt,QPropertyAnimation,QEasingCurve,Property,Signal
from PySide6.QtGui import QFont, QPixmap, QPainter, QTransform, QShowEvent
from time import sleep

from core.setting import BASEPATH
from signalObject import noticeSignal

class initNotice(QWidget):
    showMainWindow = Signal()
    def __init__(self,parent=None):
        super().__init__(parent)
        self.closeSignal = noticeSignal()

        self.logo = LogoImg(parent=self)
        self.initSetUp()

    def initSetUp(self):
        self.setObjectName('initNotice')
        self.setFixedSize(250,250)
        self.setAttribute(Qt.WA_StyledBackground, True)  # 支持qss设置背景
        self.setCursor(QPixmap('./img/mouse.png'))


        self.logo.imgAmimation.start()

    @classmethod
    def getShowPixmap(cls, path: str, width: int = 600, height: int = 300):
        return QPixmap(path).scaled(width,
                                    height,
                                    Qt.AspectRatioMode.IgnoreAspectRatio,
                                    Qt.TransformationMode.SmoothTransformation)

    def cmdinit(self):
        isCloseFunc = False
        def closeCMD():
            nonlocal isCloseFunc

            sleep(150)

            cmd.kill()
            self.closeSignal.closeNotice.emit(False)

            with open('../log/initLog', 'w', encoding='utf-8') as data:
                data.write('isInitSuccess:False')

            isCloseFunc = True

        cmd = subprocess.Popen(
            '../steamcmd/steamcmd',
            encoding='utf-8',
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            creationflags=0x08000000

        )

        stopFuncThreading = threading.Thread(target=closeCMD,daemon=True)
        stopFuncThreading.start()

        while True:
            out = cmd.stdout.readline().strip()

            if isCloseFunc:
                break
            elif out == 'Loading Steam API...OK':
                cmd.kill()
                self.closeSignal.closeNotice.emit(True)

                with open('../log/initLog','w',encoding='utf-8') as data:
                    data.write('isInitSuccess:True')

                return True
            elif '!!! Fatal Error: Steam needs to be online to update.  Please confirm your network connection and try again.' in out:
                with open('../log/initLog','w',encoding='utf-8') as data:
                    data.write('isInitSuccess:False\nerro:SteamCMD需要更新,请检查网络并重试！')

                self.closeSignal.closeNotice.emit(False)
                return False

    def workshopDirInit(self):
        downloadBase = BASEPATH + os.path.normpath('/steamcmd/steamapps/workshop')
        shutil.rmtree(downloadBase)
        os.mkdir(downloadBase)
        self.closeSignal.closeNotice.emit(True)

    def startWorkshopDirinit(self):
        initThreading = threading.Thread(target=self.workshopDirInit, daemon=True)
        initThreading.start()

    def startinit(self):
        initThreading = threading.Thread(target=self.cmdinit, daemon=True)
        initThreading.start()


class LogoImg(QLabel):
    def __init__(self,width:int=250,height:int=250,parent=None):
        super().__init__(parent)
        self._width = width
        self._height = height

        self.angle = 0

        self.initSetUp()

        self.imgAmimation = QPropertyAnimation(self,b'angle')
        self.imgAmimation.setDuration(960)
        self.imgAmimation.setStartValue(0)
        self.imgAmimation.setEndValue(360)
        self.imgAmimation.setEasingCurve(QEasingCurve.Type.InOutBack)
        self.imgAmimation.setLoopCount(-1)

    def initSetUp(self):
        self.setFixedSize(self._width,self._height)

    @Property(int)
    def angle(self):
        return self._angle

    @angle.setter
    def angle(self,value):
        self._angle = value
        self.update()

    def paintEvent(self, event):
        painter = QPainter(self)
        pixmap = QPixmap('./img/terminal-solid-156.png')
        x,y = (self.geometry().size()-pixmap.size()).toTuple()
        painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
        painter.translate(self._width/2,self._height/2)
        painter.rotate(self.angle)
        painter.translate(-self._width/2,-self._height/2)
        painter.drawPixmap(x/2,y/2,pixmap)
